package com.wx.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.wx.rabbitmq.MqConnection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.wx.rabbitmq.confirm.Consumer.EXCHANGE_DIREC_CONFIRM;

/**
 * @author wx
 * @Description: 生产者-confirm机制  confirm确认消息机制，指生产者发送消息给队列，队列收到后会给生产者回送应答，
 * 根据应答结果确认这条消息是否正常发送到队列，这种方式也是消息可靠性投递的核心保障
 * @date 2018/11/23 002316:57
 */
public class Producer {
    public static void main(String[] agrs) throws IOException, TimeoutException {
        //1.获取connection
        Connection connection = MqConnection.getConnection();

        //2.通过connection创建一个Channel
        Channel channel = connection.createChannel();
        //3.指定我们的消息投递模式: 消息的确认模式
        channel.confirmSelect();
        //4. 通过Channel发送数据   exchange=交换机、 2 routingKey=队列对应的key、3 props = 消息装饰器、 4=消息体
        String routingKey = "confirm.save";
        String msg = "Hello RabbitMQ Send confirm message!";
        channel.basicPublish(EXCHANGE_DIREC_CONFIRM, routingKey, null, msg.getBytes());
        //5.添加一个确认消息确认监听(异步)
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                //队列服务异常、磁盘满了、队列容量慢了 会出现失败回调此方法
                System.err.println("-------发送队列失败-----------");
            }

            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------成功发送到队列-----------");
            }
        });
        System.out.println("异步监听------------------------------");
    }
}
